<?php

namespace App\Http\Controllers\Web\Issue;

use App\Http\Responses\RespondsJson;
use App\Models\Issue\Issue;
use App\Models\Issue\IssueService;
use App\Models\Issue\OptionService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class IssueController extends Controller
{
    use RespondsJson;
    protected $issue;
    protected $option;

    public function __construct(IssueService $issue, OptionService $option)
    {
        $this->issue = $issue;
        $this->option = $option;
    }

    public function many()
    {
    }

    public function create(Request $request)
    {
        $this->runValidate($request);

        $id = $this->issue->createAndGetId($request->all());

        if ($id) {
            return $this->respondJson('创建成功');
        }

        return $this->respondJson('创建失败', 406);
    }

    public function update(Request $request, $id)
    {
        $this->runValidate($request);

        $data = $request->all();

        if ($this->issue->update($id, $data)) {
            return $this->respondJson('修改成功');
        }

        return $this->respondJson('修改失败', 406);
    }

    public function delete($id)
    {
        try {
            DB::beginTransaction();
            $this->option->deleteByIssue($id);
            $this->issue->delete($id);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->respondJson('删除失败', 406);
        }

        return $this->respondJson('删除成功');
    }

    protected function runValidate(Request $request)
    {
        $this->validate($request, [
            'type' => 'integer|in:1,2',
            'title' => 'required|max:255',
        ], [
            'title.required' => '请填写标题',
            'title.max' => '标题最多只能填写255字',
        ]);
    }
}
